// src/router/index.js
import { createRouter, createWebHistory } from 'vue-router';
import { useAppStore } from '@/store/modules/app';

const router = createRouter({
    history: createWebHistory(),
    routes: [
        { path: '/', name: '首页', component: () => import('../layout/index.vue'),
            children:[
                {
                    path: '/userCenter',
                    name: '个人中心',
                    component: () => import('../view/userCenter/index.vue')
                },
            ]
        },
        { path: '/login', component: () => import('@/view/Login.vue') },
        //{ path: '/test/test', component: () => import('@/view/test/test.vue') }
    ]
});

// 辅助函数：将菜单数据转换为路由配置
/*const convertMenuToRoutes = (menu) => {
    let newRoutes= router.options.routes;
    menu.forEach(item => {
        if (item.children && item.children.length > 0) {
            item.children.forEach(child => {
                if (child.component) {
                    let route = {
                        path: child.path,
                        name: child.name,
                        component: () => import(`@/view/${child.component}.vue`),
                        meta:{
                            parentName:item.name
                        }
                    };

                    console.log('child.component',child.component)
                    newRoutes[0].children.push(route);
                }
            })
        }
    })
       //return newRoutes ;
    newRoutes.forEach(route => {
        router.addRoute(route);
    })
}*/

const generateRouter = (menu) => {
    let newRouters = menu.map((r)=>{
        let routes = {
            path:r.path,
            name:r.name,
            component:()=>import(`@/views/${r.name}.vue`)//利用字符串模板拼接
        }
        if(r.children){//如果该结点有孩子，则继续递归
            routes.children = generateRouter(r.children)
        }
        return routes
    })
    return newRouters
}

/*
// 动态添加路由
router.beforeEach(async (to, from, next) => {
    const appStore = useAppStore();
    const whiteList = ['/login'];

    if (appStore.token) {
        console.log('appStore.token:',appStore.token)
        console.log('appStore.hasRoutes:',appStore.hasRoutes)
        if (!appStore.hasRoutes) {
            // 从服务器获取路由和菜单数据
            try {
                //nst response = await fetch('/api/menu'); // 假设这是获取菜单数据的 API
                //const menuData = await response.json();
               //const menuData=appStore.menu.json();

                //appStore.setRoutes(convertMenuToRoutes(menuData));
                console.log('appStore.menu:', JSON.stringify(appStore.menu))
                // 添加路由
                convertMenuToRoutes(appStore.menu);
                appStore.setHasRoutes(true);
                next();
            } catch (error) {
                console.error('Failed to fetch menu data:', error);
                next('/login');
            }
        } else {
            next();
        }
        console.log('router:',router)
    } else if (whiteList.includes(to.path)) {
        next();
    } else {
        next("/login");
    }
});
*/
router.beforeEach(async(to,from,next) =>{
    const appStore = useAppStore();
    if(!appStore.hasRoutes){//如果还没有权限
        await store.dispatch('user/getRouter')
        const newRoutes = generateRouter(store.state.user.routerList)
        newRoutes.map((item)=>{
            router.addRoute(item)
        })
        next({path:to.path})//前往当前输入的链接所在的页面
    }else{//当权限存在，直接放行
        next()
    }
})

export default router;
